package tq.com.tqstudent.views;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SPUtils;
import com.makeramen.roundedimageview.RoundedImageView;

import tq.com.tqstudent.R;

/**
 * @Author rames
 * @date 2019/3/27 15:18
 */
public class InputConflictView  extends LinearLayout {
    private static final String SHARE_NAME = "share_name";
    private static final String COLUMN_NAME = "column_name";
    private InputMethodManager imm;
    private Context mContext;
    private EditText mEditText;//输入框
    private RecyclerView recyclerView;//列表
    private View mPanelView;//跟输入法切换的面板
    private RoundedImageView mSwitchBtn;//切换面板和键盘的按钮
    private RoundedImageView groupIV; // 群组
    private int mEditTextId;
    private int mListViewId;
    private int mPanelViewId;
    private int mSwitchBtnId;
    private int mLeftViewId;
    private boolean isSend = false; // 发送按钮是否显示了
    private boolean mIsKeyboardActive = false; //　输入法是否激活
    private KeyboardOnGlobalChangeListener mKeyboardListener;
    private OnViewClickListener listener;

    public InputConflictView(Context context) {
        super(context);
        this.mContext = context;
        init(null);
    }

    public InputConflictView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init(attrs);
    }

    public InputConflictView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        //监听布局变化
        getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardOnGlobalChangeListener());
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        TypedArray custom = getContext().obtainStyledAttributes(attrs, R.styleable.InputConflictView);
        mEditTextId = custom.getResourceId(R.styleable.InputConflictView_editText, NO_ID);
        mListViewId = custom.getResourceId(R.styleable.InputConflictView_recyclerView, NO_ID);
        mPanelViewId = custom.getResourceId(R.styleable.InputConflictView_panelView, NO_ID);
        mSwitchBtnId = custom.getResourceId(R.styleable.InputConflictView_switchBtn, NO_ID);
        mLeftViewId = custom.getResourceId(R.styleable.InputConflictView_leftView, NO_ID);
        custom.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initView();
        initListener();
    }

    public void setOnViewClickListener(OnViewClickListener listener){
        this.listener = listener;
    }

    private void initView() {
        if (mEditTextId != NO_ID) {
            mEditText = findViewById(mEditTextId);
        }

        if (mListViewId != NO_ID) {
            recyclerView = findViewById(mListViewId);
        }

        if (mPanelViewId != NO_ID) {
            mPanelView = findViewById(mPanelViewId);
            int keyboardHeight = SPUtils.getInstance(getContext()).getInt(COLUMN_NAME);
            if (keyboardHeight > 0) {
                ViewGroup.LayoutParams params = mPanelView.getLayoutParams();
                params.height = keyboardHeight;
                mPanelView.setLayoutParams(params);
            }
        }

        if (mSwitchBtnId != NO_ID) {
            mSwitchBtn = findViewById(mSwitchBtnId);
        }

        if(mLeftViewId != NO_ID){
            groupIV = findViewById(mLeftViewId);
        }
    }

    public RoundedImageView getGroupIV() {
        return groupIV;
    }

    private void initListener() {
        recyclerView.setOnTouchListener(new View.OnTouchListener(){
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    hideKeyboard();
                    mPanelView.setVisibility(View.GONE);
//                  mSwitchBtn.setBackgroundResource(R.drawable.icon_more);
                    return false;
                }
            }
        );

        groupIV.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null == listener) return;
                listener.onClick(3);
            }
        });

        mSwitchBtn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        mSwitchBtn.setSelected(!mSwitchBtn.isSelected());
                        if(null == listener) return;

                        // 如果是发送按钮
                        if(isSend){
                            listener.onClick(1);
                        } else {
                            listener.onClick(2);
                        }
//                        if (mIsKeyboardActive) { // 输入法打开状态下
//                            if (mSwitchBtn.isSelected()) { // 打开表情
////                                mSwitchBtn.setBackgroundResource(R.drawable.icon_key);
//                                // 设置为不会调整大小，以便输入弹起时布局不会改变。若不设置此属性，输入法弹起时布局会闪一下
//                                ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//                                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                                imm.hideSoftInputFromWindow(mEditText.getApplicationWindowToken(), 0);
//                                mPanelView.setVisibility(View.VISIBLE);
//                            } else {
////                                mSwitchBtn.setBackgroundResource(R.drawable.icon_more);
//                                mPanelView.setVisibility(View.GONE);
//                                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                                imm.hideSoftInputFromWindow(mEditText.getApplicationWindowToken(), 0);
//                                ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
//                                        | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//                            }
//                        } else {
//                            //  输入法关闭状态下
//                            if (mSwitchBtn.isSelected()) {
////                                mSwitchBtn.setBackgroundResource(R.drawable.icon_key);
//                                // 设置为不会调整大小，以便输入弹起时布局不会改变。若不设置此属性，输入法弹起时布局会闪一下
//                                ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//                                mPanelView.setVisibility(View.VISIBLE);
//                            } else {
////                                mSwitchBtn.setBackgroundResource(R.drawable.icon_more);
//                                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);
//                                mSwitchBtn.postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() { // 输入法弹出之后，重新调整
//                                        mPanelView.setVisibility(View.GONE);
//                                        ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
//                                                | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//                                    }
//                                }, 250); // 延迟一段时间，等待输入法完全弹出*/
//                            }
//                        }
                    }
                }

        );

        mEditText.setOnClickListener(new View.OnClickListener(){
                 @Override
                 public void onClick(View v) {
                     mEditText.setCursorVisible(true);
//                   mSwitchBtn.setBackgroundResource(R.drawable.icon_more);
                     mEditText.postDelayed(new Runnable() {
                         @Override
                         public void run() {
//                             mSwitchBtn.setSelected(false);
                             if(listener!=null){
                                 listener.onClick(4);
                             }
                             mPanelView.setVisibility(View.GONE);
                             // 输入法弹出之后，重新调整
                             ((Activity) mContext).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                                     | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                         }
                     }, 250); // 延迟一段时间，等待输入法完全弹出
                 }
             }
        );

        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // 有内容了
                if(charSequence.length() > 0){
                    if(!isSend) {
                        mSwitchBtn.setImageResource(R.mipmap.icon_send);
                    }
                    isSend = true;
                } else {
                    isSend = false;
                    mSwitchBtn.setImageResource(R.mipmap.icon_take_photo);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    public interface OnViewClickListener{
        void onClick(int index);
    }

    private class KeyboardOnGlobalChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {
        int mScreenHeight = 0;
        Rect mRect = new Rect();

        private int getScreenHeight() {
            if (mScreenHeight > 0) {
                return mScreenHeight;
            }
            mScreenHeight = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();
            return mScreenHeight;
        }

        @Override
        public void onGlobalLayout() {
            // 获取当前页面窗口的显示范围
            getWindowVisibleDisplayFrame(mRect);
            int screenHeight = getScreenHeight();
            int keyboardHeight = screenHeight - mRect.bottom; // 输入法的高度
            boolean isActive = false;
            if (Math.abs(keyboardHeight) > screenHeight / 5) {
                isActive = true; // 超过屏幕五分之一则表示弹出了输入法
            }
            mIsKeyboardActive = isActive;
            LogUtil.e("screenHeight: "+screenHeight+" | 输入法高度:"+keyboardHeight);
//            onKeyboardStateChanged(mIsKeyboardActive, keyboardHeight);
        }
    }

    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getApplicationWindowToken(), 0);
    }

    private void onKeyboardStateChanged(boolean isActive, int keyboardHeight) {
        if (isActive) {
            mSwitchBtn.setFocusable(false);
            mSwitchBtn.setFocusableInTouchMode(false);
            mEditText.requestFocus();
            if (mSwitchBtn.isSelected()) { // 表情打开状态下
                mPanelView.setVisibility(View.GONE);
                mSwitchBtn.setSelected(false);
            }
            SPUtils.getInstance(getContext()).putInt(COLUMN_NAME, keyboardHeight);
            ViewGroup.LayoutParams params = mPanelView.getLayoutParams();
            if (!(params.height == keyboardHeight)) {
                params.height = keyboardHeight;
                mPanelView.setLayoutParams(params);
            }
        } else {
            if (mSwitchBtn.isSelected()) {
                return;
            }
        }
    }
}
